package com.itheima.huikebackend.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.huikebackend.common.PageResult;
import com.itheima.huikebackend.common.Result;
import com.itheima.huikebackend.dto.CoursePageQueryDTO;
import com.itheima.huikebackend.entity.Course;
import com.itheima.huikebackend.mapper.CourseMapper;
import com.itheima.huikebackend.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author Du leilei
 * @version 1.0
 * @Description
 * @createTime 2023年08月08日 17:33:00
 */
@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Override
    public  HashMap<String , Object>  page(CoursePageQueryDTO coursePageQueryDTO) {
        PageHelper.startPage(coursePageQueryDTO.getPageNum(), coursePageQueryDTO.getPageSize());
        Page<Course> coursePage =  courseMapper.page(coursePageQueryDTO);


        HashMap<String, Object> map = new HashMap<>();
        map.put("total",coursePage.getTotal());
        map.put("rows",coursePage.getResult());

        return map;
    }

    @Override
    public void addCourse(Course course) {
        int maxNum = 36;
        int i;
        int count = 0;
        char[] str = {'a', 'b', 'c', 'd', 'e', 'f', 'g',
                'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
                'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
                'x', 'y', 'z', '0', '1', '2', '3', '4',
                '5', '6', '7', '8', '9'};
        StringBuffer pwd = new StringBuffer("");
        Random r = new Random();
        while (count < 8) {
            i = Math.abs(r.nextInt(maxNum));
            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count++;
            }
        }
        course.setCode(pwd.toString());
        course.setCreateTime(LocalDateTime.now());
        courseMapper.insert(course);
    }

    @Override
    public void deleteById(Long[] ids) {
        courseMapper.deleteById(ids);
    }

    @Override
    public Course selectCourse(Long id) {
        Course course = courseMapper.selectCourse(id);
        return course;
    }

    @Override
    public void updateCourse(Course course) {
        courseMapper.updateCourse(course);
    }

    @Override
    public Course listselect(String subject) {
        Course course = new Course();
        if (subject != null) {
            course.setSubject(subject);
        }
       Course course1=  courseMapper.listselect(course);
        return course1;
    }


}
